package gw.com.android.presenter;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.chart.output.utils.ChartConfig;
import com.gwtsz.gts2.hx.R;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.Set;

import cn.jpush.android.api.TagAliasCallback;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.greendao.NotifyDataHelper;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.MainActivity;
import gw.com.android.ui.PraiseAndTransmitAdapter;
import gw.com.android.ui.dialog.BindCustomerDialog;
import gw.com.android.ui.dialog.BindEnterPasswordDialog;
import gw.com.android.ui.dialog.BottomChangeAccountDialog;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.gesture_pwd.consts.GesturePwdConst;
import gw.com.android.ui.me.PhoneNumber;
import gw.com.android.utils.CacheUtils;
import gw.com.android.utils.DataCollection;
import gw.com.android.utils.OpenApi;
import gw.com.android.utils.PackStatis;
import gw.com.android.utils.PayegisUtil;
import gw.com.android.utils.ServerConnnectUtil;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import www.com.library.app.AppActivities;
import www.com.library.app.Logger;
import www.com.library.app.ObjectSessionStore;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.AESCrypto;
import www.com.library.util.AESCrypto3;
import www.com.library.util.DeviceUtil;
import www.com.library.util.Md5;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.StringFormatter;
import www.com.library.util.StringUtils;
import www.com.library.view.BtnClickListener;
import www.com.library.view.RecyclerClickListener;

/**
 * Created by reeta.zou on 2016/11/28.
 * 自动登录的逻辑处理
 */
public class LoginPresenter extends BasePresenter {
    private final String TAG = LoginPresenter.class.getSimpleName();

    /**
     * 标识是否已经点击登录按钮
     */
    public boolean isClickLogin = false;
    public String mCurName = "";
    public String mPassword = "";
    public String mCurLoginPhone = "";
    public boolean isLoading = false;

    public LoginPresenter(Activity activity) {
        init();
        mContext = activity;
        mCurName = GTConfig.instance().getLoginName();
        mPassword = GTConfig.instance().getLoginPass(mCurName);
    }

    public void setPresenterImpl(PresenterImpl loginImpl) {
        super.setPresenterImpl(loginImpl);
        if (null != loginImpl) {
            rxBusRegister = RxBus.getInstance().register(GTSConst.REPLY_LOGIN_RESULT + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Bundle>() {

                        @Override
                        public void accept(@NonNull Bundle bundle) throws Exception {
                            onResultPresenter(bundle);
                        }
                    });
        }
    }

    @Override
    public void onResultPresenter(Bundle bundle) {
        Logger.i(TAG, "onResultPresenter 登录回包接收到回调" + mContext);
        int result = bundle.getInt("iNotification");
        if (result == AppContances.LOGIN_OK) {
            Logger.i(TAG, "login success.type = " + GTConfig.instance().getAccountType() + " account = " + GTConfig.instance().mCurName);
            saveLoginName();
            GTConfig.instance().readUserPreference();
            ChartConfig.instance().readPrefrence(AppMain.getApp(), mCurName);
            if (null != mRequestImpl) {
                mRequestImpl.onRequestSuc("");
            } else {
                Logger.i(TAG, "登录回包接收到回调 mRequestImpl is null");
            }
            OpenApi.isAccountActive();
            StringFormatter.instance().updateZone(AppTerminal.instance().getZoneType());
            GTConfig.instance().mSession = buildSession();
            if (GTConfig.instance().mCurName.length() > 0) {
                DataCollection.start(AppMain.getApp());
                // 设置极光推送标签和别名
                GTConfig.instance().setJpushAliasAndTags(mAliasCallback, GTConfig.instance().mCurName);
                PackStatis.ocpcActivate();
                PackStatis.getToService(PackStatis.EventAction.LOGIN.getValue(), PackStatis.EventCategory.MAIN.getValue(), null, null);
            }
            if (GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_GUEST) {
                GTConfig.instance().setBooleanValue(GTConfig.PREF_AUTO_LOGIN, true);//登录成功了，那么就开启自动登录
                NoviceWelfarePresenter.getInstance().cancel();
            }
            PayegisUtil.trackEvent("login");
            PackStatis.ocpcActivate();
            OpenApi.generateToken(0);
            NotifyDataHelper.notifyChange();

            try {
                //在这里判定，当前用户的手势密码是否已经设置
                String res = CacheUtils.readFile(CacheUtils.get_CACHE_GESTURE_PWD_INT());
                if (TextUtils.isEmpty(res)) {//如果为空，则没有设置，就要进入设置界面
                    ActivityManager.dispatchGesture("dispatchGestureTag2:auto", mContext, GesturePwdConst.MODE_SETTING);
                } else {//如果不为空，则是已经设置了，就进入校验模式
                    ActivityManager.dispatchGesture("dispatchGestureTag2:pwdChecking", mContext, GesturePwdConst.MODE_CHECK);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            RxBus.getInstance().post(GTSConst.REPLY_SWITCH_LOGIN_TYPE, GTConfig.instance().getAccountType());
        } else {
            Logger.i(TAG, "onResultPresenter login failed");
            if (null != mRequestImpl) {
                mRequestImpl.onRequestFail(bundle.getInt("iValue"));
            }
        }
        if (null != rxBusRegister && !rxBusRegister.isDisposed()) {
            rxBusRegister.dispose();
            rxBusRegister = null;
        }
    }

    private String buildSession() {
        String username;
        if (!TextUtils.isEmpty(mCurName)) {
            username = mCurName + System.currentTimeMillis();
        } else if (!TextUtils.isEmpty(mCurLoginPhone)) {
            username = mCurLoginPhone + System.currentTimeMillis();
        } else {
            username = "guest" + System.currentTimeMillis();
        }
        return Md5.md5(username.getBytes());
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Logger.i(TAG, logs);
                    OpenApi.pushDataByEvent(PackStatis.EventAction.LOGIN.getValue(), alias);
                    try {
                        GTConfig.instance().alias = AESCrypto3.Encrypt(alias);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Logger.i(TAG, logs);
                    if (!NetworkMonitor.hasNetWorkNoToast()) {
                        return;
                    }
                    if (mHandler != null) {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                GTConfig.instance().setJpushAliasAndTags(mAliasCallback, "");
                            }
                        }, 1000 * 60);
                    }
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Logger.e(TAG, logs);
            }
        }
    };

    /**
     * 登录界面登录功能
     */
    public void loginFun() {
        Logger.i(TAG, "loginFun");
        GTConfig.instance().mCurName = mCurName;
        GTConfig.instance().mUserPwd = mPassword;
        GTConfig.instance().mLastAccountType = GTConfig.instance().getAccountType();
        AppTerminal.instance().loginFun(AppContances.ACCOUNT_TRADE_TYPE, GTConfig.instance().getAccountType(), mCurName, mPassword);
    }

    /**
     * 登录界面手机号直接登录功能
     */
    public void phoneLoginFun() {
        Logger.i(TAG, "phoneLoginFun");
        GTConfig.instance().mCurName = "";
        GTConfig.instance().mCurLoginPhone = mCurLoginPhone;
        GTConfig.instance().mUserPwd = mPassword;

        GTConfig.instance().mLastAccountType = GTConfig.instance().getAccountType();
        AppTerminal.instance().loginFun(AppContances.ACCOUNT_MOBILE_TYPE, GTConfig.instance().getAccountType(), mCurLoginPhone, mPassword);
    }

    /**
     * 游客登录
     */
    public void guestLogin() {
        Logger.i(TAG, "guestLogin");
        PhoneNumber.getInstance().reset();
        ServerConnnectUtil.instance().isTradeConnect = true;
        GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_GUEST);
        GTConfig.instance().mLastAccountType = GTConfig.instance().getAccountType();
        AppTerminal.instance().loginFun(AppContances.ACCOUNT_TRADE_TYPE, GTConfig.instance().getAccountType(), "", "");
    }

    /**
     * 自动登录功能
     */
    public void autoLogin() {
        Logger.i(TAG, "autoLogin mCurName = " + mCurName + "-mContext:" + mContext);
        if (GTConfig.instance().getBooleanValue(GTConfig.PREF_AUTO_LOGIN, true)) {
            if (DeviceUtil.instance().isPhone(mCurName)) {
                GTConfig.instance().isPhoneLogin = true;
                GTConfig.instance().mCurLoginPhone = mCurName;
                mCurLoginPhone = mCurName;
                int lastAccountType = GTConfig.instance().getLastPhoneLoginType(mCurName);
                GTConfig.instance().setAccountType(lastAccountType);
                //获取手机号绑定的账户
                String loginName = GTConfig.instance().getPhoneLoginInfo(mCurName, lastAccountType);
                Logger.i(TAG, "autoLogin phoneNum = " + mCurName + "  account = " + loginName + "  type = " + lastAccountType);
                mCurName = loginName;
            } else {
                if (mCurName.startsWith(ConfigUtil.instance().mConfigObject.optString(ConfigType.PREFIX_DEMO_ACCOUNT))) {
                    Logger.i(TAG, "autoLogin account is demo : " + mCurName);
                    GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_DEMO);
                } else {
                    Logger.i(TAG, "autoLogin account is real : " + mCurName);
                    GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
                }
            }
            if (mCurName.length() > 0 && mPassword.length() > 0) {
                if (DeviceUtil.instance().isPhone(mCurName)) {
                    phoneLoginFun();
                } else {
                    loginFun();
                }
            } else {
                guestLogin();
            }
        } else {
            guestLogin();
        }
    }

    /**
     * 登录成功后保存账号信息
     */
    private void saveLoginName() {
        if (GTConfig.instance().getAccountType() != GTConfig.ACC_TYPE_GUEST) {
            if (GTConfig.instance().isFromLogin) {
                if (GTConfig.instance().isPhoneLogin) {
                    GTConfig.instance().saveLoginInfo(GTConfig.instance().mCurLoginPhone, mPassword);
                    Logger.i("mCurLoginPhone:::" + GTConfig.instance().mCurLoginPhone + "...mCurName:::" + mCurName);
                    GTConfig.instance().savePhoneLoginInfo(GTConfig.instance().mCurLoginPhone, mCurName);
                } else {
                    GTConfig.instance().saveLoginInfo(mCurName, mPassword);
                }
                GTConfig.instance().isFromLogin = false;
            } else {
                if (GTConfig.instance().isPhoneLogin) {
                    GTConfig.instance().saveLoginType(GTConfig.instance().mCurLoginPhone);
                    GTConfig.instance().savePhoneLoginInfo(GTConfig.instance().mCurLoginPhone, mCurName);
                } else {
                    GTConfig.instance().saveLoginType(mCurName);
                }
            }
            CrashReport.setUserId(mCurName);
            PraiseAndTransmitAdapter.initLocalMap();// 重新登录，必须清除缓存中的点赞信息
        }
    }

    /**
     * 网页自动登录调用
     */
    public void autoLogin(String url, final BaseActivity activity) {
        if (!NetworkMonitor.hasNetWork()) {
            return;
        }
        if (null != activity) {
            activity.showLoading();
        }
        // 解密
        String DeString = "";
        try {
            DeString = AESCrypto.Decrypt(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String userName = DeString.substring(DeString.indexOf("uid=") + 4, DeString.indexOf("&pw="));
        String userPwd = DeString.substring(DeString.indexOf("&pw=") + 4, DeString.indexOf("&type="));
        String usertype = DeString.substring(DeString.indexOf("&type=") + 6);

        Logger.i("automatic 用户名-=-=" + userName + "-=-=" + "userPwd-=-=-" + userPwd + "account_type-===" + usertype);
        GTConfig.instance().isFromLogin = true;
        GTConfig.instance().savePasswordFlag(true);
        mCurName = userName;
        mPassword = userPwd;
        if (usertype.equals("1")) {
            GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
        } else {
            GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_DEMO);
        }

        DataManager.instance().reset();
        loginFun();
        if (!(activity instanceof MainActivity)) {
            MainActivity mainActivity = (MainActivity) ObjectSessionStore.getObject(MainActivity.class.getSimpleName() + GTSDataListener.mainNum);
            if (mainActivity != null) {
                mainActivity.finish();
            }
        }
        setPresenterImpl(new PresenterImpl() {
            @Override
            public void onRequestSuc(Object result) {
                activity.hideLoading();
                if (!(activity instanceof MainActivity)) {
                    ActivityManager.showMainTab(activity, ConfigType.TAB_HOME_TAG, AppContances.FROM_LOGIN_ACTIVITY);
                    AppActivities.getSingleton().popAllActivityExceptOne(MainActivity.class.getSimpleName());
                } else {
                    MainActivity mainActivity = (MainActivity) ObjectSessionStore.getObject(MainActivity.class.getSimpleName() + GTSDataListener.mainNum);
                    if (mainActivity != null) {
                        mainActivity.hideLoading();
                        mainActivity.removeFragment();
                        mainActivity.refreshHomeWeb();
                    } else {
                        Logger.e("切换账号 getActivity() is null");
                    }
                    AppTerminal.instance().setLoginView(0);
                }
            }

            @Override
            public void onRequestFail(int failCode) {
                if (null != activity) {
                    activity.hideLoading();
                    String error;
                    if (failCode >= 1100 && failCode < 1200) {
                        error = ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1100) + failCode;
                    } else {
                        error = ConfigUtil.instance().getErrorConfigObject().optString(failCode + "");
                    }
                    PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(activity, error, new BtnClickListener() {
                        @Override
                        public void onBtnClick(int viewID) {
                            ActivityManager.backLogin(activity, true);
                        }
                    });
                    dialog.setCancelable(false);
                    dialog.show();
                }
                isLoading = false;
                setPresenterImpl(null);
            }
        });
    }

    /**
     * 登录界面返回到行情调用
     */
    public void closeLogin(Activity activity) {
        if (isClickLogin /*|| GTConfig.instance().mLastAccountType == GTConfig.ACC_TYPE_GUEST*/) {
            Logger.e("从登录界面返回，isClickLogin变成游客登录");
            GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_GUEST);
            AppActivities.getSingleton().popAllActivityExceptOne(activity.getClass().getSimpleName());
            DataManager.instance().reset();
            guestLogin();
        } else {
            if (GTConfig.instance().mLastAccountType != GTConfig.ACC_TYPE_GUEST) {
                GTConfig.instance().setAccountType(GTConfig.instance().mLastAccountType);
                if (GTConfig.instance().mUserPwd == null || GTConfig.instance().mUserPwd.length() < 1) {
                    AppActivities.getSingleton().popAllActivityExceptOne(activity.getClass().getSimpleName());
                    DataManager.instance().reset();
                    guestLogin();
                } else {
                    NetworkMonitor.hasNetWork();
                    ServerConnnectUtil.instance().hasReConnectServer();
                }
            } else {
                GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_GUEST);
                NetworkMonitor.hasNetWork();
                ServerConnnectUtil.instance().hasReConnectQuote();
            }
        }
        MainActivity mainActivity = (MainActivity) ObjectSessionStore.getObject(MainActivity.class.getSimpleName() + GTSDataListener.mainNum);
        if (null == mainActivity) {
            ActivityManager.showMainTab(activity, ConfigType.TAB_HOME_TAG, AppContances.FROM_LOGIN_ACTIVITY);
        }
        activity.finish();
    }

    /**
     * 显示账号切换弹层
     */
    public void showChangePop(Activity activity, final PresenterImpl impl) {
        final BaseActivity mActivity = (BaseActivity) activity;
        String loginAccount = "";
        if (GTConfig.instance().isPhoneLogin) {
            loginAccount = GTConfig.instance().mCurLoginPhone;
        } else {
            loginAccount = GTConfig.instance().mCurName;
        }
        BottomChangeAccountDialog.showBottomChangeAccountDialog(activity, loginAccount, new RecyclerClickListener() {
            @Override
            public void onClick(int position, DataItemDetail itemDetail) {
                if (!NetworkMonitor.hasNetWork()) {
                    return;
                }
                if (isLoading) {
                    return;
                }
                AppTerminal.instance().setLoginView(1);
                isClickLogin = true;
                isLoading = true;
                mActivity.showLoading();
                mCurName = itemDetail.getString("name");
                mPassword = itemDetail.getString("password");
                DataManager.instance().reset();
                setPresenterImpl(impl);
                GTConfig.instance().isFromLogin = true;
                if (DeviceUtil.instance().isPhone(mCurName)) {
                    GTConfig.instance().isPhoneLogin = true;
                    GTConfig.instance().mCurLoginPhone = mCurName;
                    mCurLoginPhone = mCurName;
                    if (GTConfig.instance().getLastPhoneLoginType(mCurName) == GTConfig.ACC_TYPE_DEMO) {
                        String loginName = GTConfig.instance().getPhoneLoginInfo(mCurName, GTConfig.ACC_TYPE_DEMO);
                        if (!"".equals(loginName)) {
                            mCurName = loginName;
                        }
                        GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_DEMO);

                    } else {
                        String loginName = GTConfig.instance().getPhoneLoginInfo(mCurName, GTConfig.ACC_TYPE_REAL);
                        if (!"".equals(loginName)) {
                            mCurName = loginName;
                        }
                        GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
                    }
                } else {
                    GTConfig.instance().isPhoneLogin = false;
                    GTConfig.instance().mCurLoginPhone = "";
                    if (mCurName.startsWith(ConfigUtil.instance().mConfigObject.optString(ConfigType.PREFIX_DEMO_ACCOUNT))) {
                        GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_DEMO);
                    } else {
                        GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
                    }
                }
                if (DeviceUtil.instance().isPhone(mCurName)) {
                    phoneLoginFun();
                } else {
                    loginFun();
                }

            }
        });
    }

    /**
     * 账号切换逻辑
     */
    public void accSwitchAccount(String loginName, DataItemResult itemResult, boolean isPhoneLogin, int accountType, Activity activity,
                                 BindEnterPasswordDialog.BtnConfirmListener mBtnConfirmListener) {
        String dialogContent = "";
        if (itemResult.getDataCount() > 1) {//2.1 有多个模拟账号，提示选择账号并输入密码绑定
            if (isPhoneLogin) {//手机登录，提示用户用账号登录
                return;
            } else {//账号登录
                if (accountType == GTConfig.ACC_TYPE_DEMO) {
                    dialogContent = AppMain.getAppString(R.string.title_bind_demo_account);
                } else {
                    dialogContent = AppMain.getAppString(R.string.title_bind_real_account);
                }

            }
            BindCustomerDialog.showBindCustomerDialog(activity, isPhoneLogin, dialogContent, GTConfig.ACC_TYPE_DEMO, itemResult, mBtnConfirmListener);
        } else if (itemResult.getDataCount() == 1) {//2.2 只有一个模拟账号，只需要提示输入密码并绑定即可
            DataItemDetail mDetail = itemResult.getItem(0);
            String realAccount = "";
            String demoAccount = "";
            if (accountType == GTConfig.ACC_TYPE_DEMO) {
                realAccount = loginName;
                demoAccount = mDetail.getString("customerNumber");
            } else {
                realAccount = mDetail.getString("customerNumber");
                demoAccount = loginName;
            }
            if ((isPhoneLogin || GTConfig.instance().isPhoneLogin) && !StringUtils.isEmpty(realAccount) && !StringUtils.isEmpty(demoAccount)) {//手机登录，提示用户绑定
                dialogContent = AppMain.getAppString(R.string.title_real_bind_demo_tips, realAccount, demoAccount);
            } else {//账号登录
                if (accountType == GTConfig.ACC_TYPE_DEMO) {
                    dialogContent = AppMain.getAppString(R.string.demo_bind_enter_password_account, mDetail.getString("customerNumber"));
                } else {
                    dialogContent = AppMain.getAppString(R.string.real_bind_enter_password_account, mDetail.getString("customerNumber"));
                }
            }
            BindEnterPasswordDialog.showBindEnterPasswordDialog(activity, isPhoneLogin, dialogContent, mDetail, mBtnConfirmListener);

        }
    }

    /**
     * 账号切换逻辑2,bindName需要绑定的账号
     */
    public void accSwitchAccount2(String curName, String bindName, int accountType, Activity activity, BindEnterPasswordDialog.BtnConfirmListener btnConfirmListener) {
        DataItemDetail mDetail = new DataItemDetail();
        mDetail.setStringValue("customerNumber", bindName);
        String realAccount = "";
        String demoAccount = "";
        String dialogContent = "";
        if (accountType == GTConfig.ACC_TYPE_DEMO) {//其實是要绑定真實，实际情况是登录的真实账号没绑定，而有一个绑定了的模拟
            realAccount = bindName;
            demoAccount = curName;
        } else {// 其實是要绑定模擬，实际情况是登录的模擬账号没绑定，而有一个绑定了的真實
            realAccount = curName;
            demoAccount = bindName;
        }
        if (GTConfig.instance().isPhoneLogin) {//手机登录，提示用户绑定
            dialogContent = AppMain.getAppString(R.string.title_real_bind_demo_tips, realAccount, demoAccount);
        } else {
            if (accountType == GTConfig.ACC_TYPE_DEMO) {
                dialogContent = AppMain.getAppString(R.string.demo_bind_enter_password_account, demoAccount);
            } else {
                dialogContent = AppMain.getAppString(R.string.real_bind_enter_password_account, realAccount);
            }
        }
        BindEnterPasswordDialog.showBindEnterPasswordDialog(activity, false, dialogContent, mDetail, btnConfirmListener);
    }

}
